<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>客户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主内容区域 -->
    <el-card>
      <!-- 页面标题 -->
      <el-page-header @back="goBack" content="客户列表" style="margin-bottom: 20px;"></el-page-header>
      <!-- 多条件查询表单 -->
      <el-form
          :inline="true"
          :model="queryMap"
          ref="form"
          size="small"
          style="margin-top: 2vh"
      >
        <el-row>
          <h4 style="margin: 1vh 0 2vh; color: #1f2d3d">多条件查询区</h4>
        </el-row>
        <!-- 客户名称输入框 -->
        <el-form-item>
          <el-input
              v-model="queryMap.clientName"
              clearable
              placeholder="请输入客户名称"
          ></el-input>
        </el-form-item>
        <!-- 联系人输入框 -->
        <el-form-item>
          <el-input
              v-model="queryMap.linkman"
              clearable
              placeholder="请输入联系人"
          ></el-input>
        </el-form-item>
        <!-- 客户手机输入框 -->
        <el-form-item>
          <el-input
              v-model="queryMap.phone"
              clearable
              placeholder="请输入客户手机"
          ></el-input>
        </el-form-item>
        <!-- 行业类别选择框 -->
        <el-form-item>
          <el-select
              v-model="queryMap.inDustryId"
              clearable
              placeholder="请选择行业类别"
          >
            <el-option label="全部" value="-1"></el-option>
            <el-option
                v-for="category in BgIndustryList"
                :key="category.value"
                :label="category.label"
                :value="category.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 客户来源选择框 -->
        <el-form-item>
          <el-select
              v-model="queryMap.sourceId"
              clearable
              placeholder="请选择客户来源"
          >
            <el-option label="全部" value="-1"></el-option>
            <el-option
                v-for="source in BgSourceList"
                :key="source.value"
                :label="source.label"
                :value="source.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 客户类型选择框 -->
        <el-form-item>
          <el-select
              v-model="queryMap.clientTypeId"
              clearable
              placeholder="请选择客户类型"
          >
            <el-option label="全部" value="-1"></el-option>
            <el-option
                v-for="type in BgClinetType"
                :key="type.value"
                :label="type.label"
                :value="type.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 所属销售/售后选择框 -->
        <el-form-item>
          <el-select
              v-model="queryMap.employeeIdAftermarket"
              clearable
              placeholder="请选择所属销售/售后"
          >
            <el-option label="全部" value="-1"></el-option>
            <el-option
                v-for="type in company"
                :key="type.value"
                :label="type.label"
                :value="type.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 客户编号输入框 -->
        <el-form-item>
          <el-input
              v-model="queryMap.clientNo"
              clearable
              placeholder="请输入客户编号"
          ></el-input>
        </el-form-item>
        <!-- 客户编号输入框 -->
        <el-form-item>
          <el-input
              v-model="queryMap.company"
              clearable
              placeholder="请输入所属公司"
          ></el-input>
        </el-form-item>
        <!-- 是否意向输入框 -->
        <el-form-item>
          <el-select
              clearable
              style="width: 140px;"
              v-model="queryMap.intention"
              placeholder="是否意向"
          >
            <el-option label="全部" value="-1"></el-option>
            <el-option label="否" value="0"></el-option>
            <el-option label="是" value="1"></el-option>
          </el-select>
        </el-form-item>
        <!-- 客户进线选择框 -->
        <el-form-item>
          <el-select
              v-model="queryMap.clientCoilInId"
              clearable
              placeholder="请选择客户进线"
          >
            <el-option label="全部" value="-1"></el-option>
            <el-option
                v-for="type in BgClientCoilIn"
                :key="type.value"
                :label="type.label"
                :value="type.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 创建时间日期选择器 -->
        <el-form-item label="创建时间">
          <el-date-picker
              v-model="value2"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <!-- 查询和重置按钮 -->
        <el-form-item>
          <el-button icon="el-icon-refresh" @click="reset"
                     style="background-color: #f0f0f0; color: #409EFF; border: none;">重置
          </el-button>
          <el-button type="primary" icon="el-icon-search" @click="searchCustomer">查询</el-button>
        </el-form-item>
      </el-form>
      <!-- 操作按钮区 -->
      <div style="margin-bottom: 10px; display: flex">
        <span class="hint" style="flex: 1;"></span>
        <!-- 新建客户按钮 -->
        <el-button
            type="success"
            icon="el-icon-plus"
            v-hasPermission="'ClientManage:add'"
            @click="openAddDialog"
        >
          新建客户
        </el-button>
        <!-- 删除选中客户按钮 -->
        <el-button
            type="danger"
            icon="el-icon-delete"
            v-hasPermission="'ClientManage:delete'"
            @click="deleteBgClient"
            :disabled="multipleSelection.length === 0"
        >
          删除选中
        </el-button>
      </div>
      <!-- 客户数据表格 -->
      <el-table
          ref="multipleTable"
          :data="clientData"
          size="small"
          @selection-change="handleSelectionChange"
          border
          style="width: 100%;"
          height="420"
      >
        <!-- 选择框列 -->
        <el-table-column type="selection" width="40"></el-table-column>

        <!-- 客户名称列 -->
        <el-table-column prop="clientName" label="客户名称" width="150"></el-table-column>
        <!-- 联系人列 -->
        <el-table-column prop="linkman" label="联系人" width="150"></el-table-column>
        <!-- 客户手机列 -->
        <el-table-column prop="phone" label="客户手机" width="160"></el-table-column>
        <!-- 行业类别列 -->
        <el-table-column prop="inDustryOptions" label="行业类别" width="150"></el-table-column>
        <!-- 人员规模列 -->
        <el-table-column prop="staffSize" label="人员规模" width="140"></el-table-column>
        <!-- 客户编号列 -->
        <el-table-column prop="clientNo" label="客户编号" width="120"></el-table-column>
        <!-- 售后列 -->
        <el-table-column prop="aftermarket" label="售后" width="120"></el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="150" fixed="right">
          <template v-slot="scope">
            <!-- 编辑按钮 -->
            <el-tooltip content="编辑" placement="top" effect="light">
              <el-button
                  circle
                  round
                  plain
                  size="small"
                  type="primary"
                  icon="el-icon-edit-outline"
                  v-hasPermission="'ClientManage:edit'"
                  @click="openEditDialog(scope.row)"
              ></el-button>
            </el-tooltip>
            <!-- 跟进按钮 -->
            <el-tooltip content="跟进" placement="top" effect="light">
              <el-button
                  circle
                  round
                  plain
                  icon="el-icon-edit"
                  type="success"
                  size="small"
                  v-hasPermission="'ClientManage:follow'"
                  @click="followUp(scope.row.clientId)"
              ></el-button>
            </el-tooltip>
            <!-- 关注按钮 -->
            <el-tooltip content="关注" placement="top" effect="light" v-if="scope.row.isAttention == 0">
              <el-button
                  circle
                  round
                  plain
                  icon="el-icon-star-off"
                  type="warning"
                  size="small"
                  v-hasPermission="'ClientManage:addAttention'"
                  @click="toggleFollow(scope.row.clientId)"
              ></el-button>
            </el-tooltip>

            <el-tooltip content="已关注" placement="top" effect="light" v-else>
              <el-button
                  circle
                  round
                  icon="el-icon-star-on"
                  type="warning"
                  size="small"
              ></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
          style="margin-top:10px;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryMap.pageNum"
          :page-sizes="[6, 10, 20, 30]"
          :page-size="queryMap.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
      <!-- 添加客户对话框 -->
      <el-dialog
          :title="dialogTitle"
          :visible.sync="dialogVisible"
          width="800px"
      >
        <!-- 表单内容 -->
        <el-form
            :model="clientForm"
            :rules="clientFormRules"
            ref="clientForm"
            label-width="120px"
            class="form-container"
        >
          <el-row>
            <!-- 客户名称输入 -->
            <el-col :span="11">
              <el-form-item label="客户名称" prop="clientName">
                <el-input clearable v-model="clientForm.clientName" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
            <!-- 联系人输入 -->
            <el-col :span="11" :offset="1">
              <el-form-item label="联系人" prop="linkman">
                <el-input clearable v-model="clientForm.linkman" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- 客户手机输入 -->
            <el-col :span="11">
              <el-form-item label="客户手机" prop="phone">
                <el-input clearable v-model="clientForm.phone" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="所属公司" prop="company">
                <el-input clearable v-model="clientForm.company" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- 行业类别选择 -->
            <el-col :span="11">
              <el-form-item label="行业类别" prop="inDustryId">
                <el-select
                    clearable
                    v-model="clientForm.inDustryId"
                    placeholder="请选择行业类别"
                    style="width: 100%;"
                >
                  <el-option
                      v-for="category in BgIndustryList"
                      :key="category.value"
                      :label="category.label"
                      :value="category.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 客户类别选择 -->
            <el-col :span="11" :offset="1">
              <el-form-item label="客户类别" prop="clientTypeId">
                <el-select
                    clearable
                    v-model="clientForm.clientTypeId"
                    placeholder="请选择客户类别"
                    style="width: 100%;"
                >
                  <el-option
                      v-for="type in BgClinetType"
                      :key="type.value"
                      :label="type.label"
                      :value="type.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- 客户类型选择 -->
            <el-col :span="11">
              <el-form-item label="客户进线" prop="clientCoilInId">
                <el-select
                    clearable
                    v-model="clientForm.clientCoilInId"
                    placeholder="请选择客户进线"
                    style="width: 100%;"
                >
                  <el-option
                      v-for="type in BgClientCoilIn"
                      :key="type.value"
                      :label="type.label"
                      :value="type.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- 客户来源选择 -->
            <el-col :span="11">
              <el-form-item label="客户来源" prop="sourceId">
                <el-select
                    clearable
                    v-model="clientForm.sourceId"
                    placeholder="请选择客户来源"
                    style="width: 100%;"
                >
                  <el-option
                      v-for="source in BgSourceList"
                      :key="source.value"
                      :label="source.label"
                      :value="source.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- 对话框底部按钮 -->
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取消</el-button>
    <el-button type="primary" :loading="btnLoading" :disabled="btnDisabled" @click="addBgClient">保存</el-button>
  </span>
      </el-dialog>
      <!-- 详情/修改抽屉 -->
      <el-drawer
          title="客户详情"
          :visible.sync="drawer_details"
          direction="rtl"
          size="60%"
      >
        <div style="height: 90vh;overflow: auto">
          <el-card style="margin: 0 3vh">
            <el-row>
              <el-col :span="21" style="color: #1a73e8">基本信息</el-col>
              <el-col :span="2" style="color: #1a73e8">
                <el-button type="primary" style="margin-left: 2vh" :loading="btnLoading" :disabled="btnDisabled"
                           @click="editClient">保存
                </el-button>
              </el-col>
            </el-row>
            <!-- 表单内容 -->
            <el-form
                :model="editClientForm"
                :rules="editClientFormRules"
                ref="editClientForm"
                label-width="120px"
                class="form-container"
            >
              <el-row>
                <el-col :span="8">
                  <el-form-item label="客户名称" prop="clientName">
                    <el-input clearable v-model="editClientForm.clientName" style="width: 20vh; margin-left: 1vh"
                              placeholder="请输入内容"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="联系人" prop="linkman">
                    <el-input clearable v-model="editClientForm.linkman" style="width: 20vh; margin-left: 1vh"
                              placeholder="请输入内容"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="客户电话" prop="phone">
                    <el-input clearable v-model="editClientForm.phone" style="width: 20vh; margin-left: 1vh"
                              placeholder="请输入内容"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="行业类别" prop="inDustryId">
                    <el-select clearable style="margin-left: 1vh; width: 18vh" v-model="editClientForm.inDustryId"
                               placeholder="请选择">
                      <el-option v-for="type in BgIndustryList" :key="type.value" :label="type.label"
                                 :value="type.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="客户类型" prop="clientTypeId">
                    <el-select clearable style="margin-left: 1vh; width: 18vh" v-model="editClientForm.clientTypeId"
                               placeholder="请选择">
                      <el-option v-for="type in BgClinetType" :key="type.value" :label="type.label"
                                 :value="type.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="客户状态" prop="clientStatusId">
                    <el-select clearable style="margin-left: 1vh; width: 18vh" v-model="editClientForm.clientStatusId"
                               placeholder="请选择">
                      <el-option v-for="type in BgClientStatus" :key="type.value" :label="type.label"
                                 :value="type.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="客户来源" prop="sourceId">
                    <el-select clearable style="margin-left: 1vh; width: 18vh" v-model="editClientForm.sourceId"
                               placeholder="请选择">
                      <el-option v-for="type in BgSourceList" :key="type.value" :label="type.label"
                                 :value="type.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="客户进线" prop="clientCoilInId">
                    <el-select clearable style="margin-left: 1vh; width: 18vh" v-model="editClientForm.clientCoilInId"
                               placeholder="请选择">
                      <el-option v-for="type in BgClientCoilIn" :key="type.value" :label="type.label"
                                 :value="type.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="是否意向" prop="intention">
                    <el-select clearable style="margin-left: 1vh; width: 18vh" v-model="editClientForm.intention"
                               placeholder="请选择">
                      <el-option label="否" :value="0"></el-option>
                      <el-option label="是" :value="1"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-form-item label="所属公司" prop="company">
                    <el-input clearable v-model="editClientForm.company" style="width: 40vw; margin-left: 1vh"
                              placeholder="请输入内容"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" style="width: 49vw; margin-left: 1vh"
                              :autosize="{ minRows: 4, maxRows: 8}" placeholder="请输入内容"
                              v-model="editClientForm.remark"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

            </el-form>
          </el-card>
          <el-card style="margin: 3vh">
            <el-row>
              <el-col :span="24" style="color: #1a73e8">跟进时间线</el-col>
            </el-row>
            <div class="block">
              <el-timeline>
                <el-timeline-item
                    v-for="(item, index) in clientFollowList"
                    :key="index"
                    :timestamp="item.followTime.slice(0, 10)"
                    placement="top">
                  <el-card>
                    <h4>{{ item.followContent }}</h4>
                    <p>{{ item.nick_name }} 提交于 {{ item.followTime.slice(0, 10) }}
                      {{ item.followTime.slice(11, 16) }}</p>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-card>
        </div>
      </el-drawer>
      <!-- 跟进客户弹出层 -->
      <div v-if="isVisible_follow" class="popups" @click.self="isVisible_follow=false">
        <el-main style="width: 550px;height: 300px">
          <div class="header">
            <h3 style="flex: 1"> 客户</h3>
            <el-tooltip content="关闭页面" placement="top" effect="light">
              <el-button icon="el-icon-circle-close" circle @click="isVisible_follow=false"></el-button>
            </el-tooltip>
          </div>
          <div>
            <el-form :inline="true" ref="form" size="small" style="margin-top: 2vh;padding: 2vh 6vh">
              <el-form-item label="跟进内容">
                <el-input
                    v-model="clientFollow.followContent"
                    type="textarea"
                    placeholder="请输入内容"
                    style="width: 40vh"
                    maxlength="200"
                    show-word-limit
                >
                </el-input>
                <span style="color: red"> *</span>
              </el-form-item>
              <el-form-item label="提醒时间">
                <el-date-picker
                    v-model="clientFollow.remindTime"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item style="margin-left:2vh">
                <el-button :loading="btnLoading" :disabled="btnDisabled" @click="addClientFollow" type="primary">保存
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-main>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      value: '',
      isVisible_follow: false,
      dialogVisible: false, // 控制对话框显示与隐藏
      drawer_details: false,
      btnLoading: false,
      btnDisabled: false,
      dialogTitle: "新建客户", // 对话框标题
      clientData: [], // 客户数据列表
      BgIndustryList: [],
      BgSourceList: [],
      BgClientCoilIn: [],
      BgClinetType: [],
      company: [],
      BgClientStatus: [],
      value2: [],//日期选择器
      multipleSelection: [], // 选中的客户数据
      clientFollowList: [],   //客户跟进数据
      total: 0, // 总客户数
      queryMap: {
        pageNum: 1, // 当前页码
        pageSize: 10, // 每页显示条数
        clientName: '',
        linkman: '',
        phone: null,
        inDustryId: null,
        sourceId: null,
        clientTypeId: null,
        employeeIdAftermarket: null,
        clientNo: '',
        intention: null,
        // 1111
        clientCoilInId: null,
        startTime: '',
        endTime: '',
      },
      clientForm: {
        clientName: "", // 客户名称
        linkman: "", // 联系人
        phone: "", // 客户手机
        company: "", //所属公司
        inDustryId: null,
        clientTypeId: null,
        clientCoilInId: null,
        sourceId: null,
      },
      editClientForm: {
        clientId: null,
        clientName: "", // 客户名称
        linkman: "", // 联系人
        phone: "", // 客户手机
        company: "", //公司
        remark: "",  //备注
        inDustryId: null,
        clientTypeId: null,
        clientCoilInId: null,
        sourceId: null,
        clientStatusId: null,
        intention: null
      },
      clientFollow: {
        clientId: null,
        followContent: '',
        remindTime: '',
      },
      clientFormRules: {
        clientName: [
          {required: true, message: '请输入客户名称', trigger: 'blur'}
        ],
        linkman: [
          {required: true, message: '请输入联系人', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入客户手机', trigger: 'blur'},
          {pattern: /^(?:\+86|0086)?\s*-?\s*(?:(?:1[3-9]\d{9})|(?:0\d{2,3}-\d{7,8})|(?:0\d{10}))$/, message: '请输入有效的手机号码', trigger: 'blur'}
        ],
      },
      editClientFormRules: {
        clientName: [
          {required: true, message: '请输入客户名称', trigger: 'blur'}
        ],
        linkman: [
          {required: true, message: '请输入联系人', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入客户手机', trigger: 'blur'},
          {pattern: /^(?:\+86|0086)?\s*-?\s*(?:(?:1[3-9]\d{9})|(?:0\d{2,3}-\d{7,8})|(?:0\d{10}))$/, message: '请输入有效的手机号码', trigger: 'blur'}
        ]
      },
    }
  },
  methods: {
    // 返回上一页
    goBack() {
      console.log("返回上一页");
    },
    /**
     * 获取客户列表数据
     * 使用模拟数据，并进行分页处理
     */
    async getClientList() {
      const {data: res} = await this.$http.get(
          "bgClient/findList",
          {
            params: this.queryMap
          }
      );
      if (!res.success) {
        return this.$message.error("获取用户列表失败:" + res.data.errorMsg);
      } else {
        this.total = res.data.total;
        this.clientData = res.data.rows;
        console.log(this.clientData)
      }
    },
    // 添加客户跟进
    async addClientFollow() {
      this.btnLoading = true;
      this.btnDisabled = true;
      const isOk = this.clientFollow.followContent != null && this.clientFollow.followContent != ''
      if (isOk) {
        const response = await this.$http.post("bgClient/addBgClientFollow", this.clientFollow)
        console.log(this.clientFollow.remindTime)
        if (response.data.success == 1) {
          this.$message.success('添加客户跟进成功！');
          this.btnLoading = false;
          this.btnDisabled = false;
          this.isVisible_follow = false
        } else {
          this.btnLoading = false;
          this.btnDisabled = false;
          this.$message.error(response.data.message);
        }
      } else {
        this.btnLoading = false;
        this.btnDisabled = false;
        this.$message.error("请输入完整信息");
      }
    },
    //添加客户
    async addBgClient() {
      const valid = await this.$refs.clientForm.validate();
      if (valid) {
        this.btnLoading = true;
        this.btnDisabled = true;
        const {data: res} = await this.$http.post(
            "bgClient/addBgClients", this.clientForm
        );
        if (res > 0) {
          await this.getClientList(); // 刷新客户列表
          this.btnLoading = false;
          this.btnDisabled = false;
          this.dialogVisible = false; // 关闭对话框
          this.clearAddClientData();
          this.$message.success("添加成功！");
        } else {
          this.btnLoading = false;
          this.btnDisabled = false;
          this.$message.error("添加失败！");
        }
      } else {
        this.btnLoading = false;
        this.btnDisabled = false;
        this.$message.error("请填写必填项！");
      }
    },
    //修改客户
    async editClient() {
      // 表单验证
      const valid = await this.$refs.editClientForm.validate();
      if (valid) {
        this.btnLoading = true;
        this.btnDisabled = true;
        const {data: res} = await this.$http.post(
            "bgClient/editBgClient", this.editClientForm
        );
        if (res > 0) {
          await this.getClientList();
          this.btnLoading = false;
          this.btnDisabled = false;
          this.drawer_details = false;
          this.$message.success("修改成功！");
        } else {
          this.btnLoading = false;
          this.btnDisabled = false;
          this.$message.error("修改失败！");
        }
      } else {
        this.btnLoading = false;
        this.btnDisabled = false;
        this.$message.error("请填写必填项！");
      }
    },
    //获取客户跟进详情
    async getClientFollow(clientId) {
      const {data: res} = await this.$http.get(
          "bgClient/getBgClientFollowListByClientId", {
            params: {clientId: clientId}
          }
      );
      if (!res.success) {
        return this.$message.error("获取客户跟进详情失败:" + res.data.errorMsg);
      } else {
        this.clientFollowList = res.data
      }
    },
    //关注
    async toggleFollow(clientId) {
      const {data: res} = await this.$http.post(
          "bgClient/addAttention", clientId
      );
      if (res > 0) {
        // await this.getClientList();
        this.drawer_details = false
        this.getClientList()
        return this.$message.success("关注成功！");
      } else {
        return this.$message.error("关注失败！");
      }
    },
    //批量删除客户
    async deleteBgClient() {
      // 将选中的客户 ID 包装成数组
      const payload = this.multipleSelection.map(item => item.clientId); // 获取选中的客户 ID 数组
      console.log(payload)
      if (payload.length > 0) {
        // 弹出确认框，询问用户是否确认删除
        const confirmResult = await this.$confirm('确认要批量删除该客户吗？此操作不可恢复，请谨慎操作', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        if (confirmResult === 'confirm') {
          // 发送批量删除请求
          const {data: res} = await this.$http.post("bgClient/deleteBgClients", payload);

          if (res > 0) {
            this.$message.success(`删除成功，共成功删除 ${res} 个客户`);
            // 更新列表或执行其他操作
            this.getClientList();
          } else {
            this.$message.error('删除失败，没有客户被成功删除');
          }
        } else {
          this.$message.info('已取消删除操作');
        }
      } else {
        this.$message.error("您没有选择客户");
      }
    },
    //加载行业类型列表
    async getAllBgIndustryList() {
      this.loading = true;
      const {data: res} = await this.$http.get("/bgClient/findBgIndustryList");
      let validData = [];
      if (Array.isArray(res)) {
        validData = res;
      } else if (typeof res === 'object' && res.success) {
        validData = res.data || [];
      }
      if (Array.isArray(validData)) {
        this.BgIndustryList = validData.map(item => ({
          value: item.inDustryId,
          label: item.options
        }));
      }
    },
    //加载客户类型列表
    async getAllBgClientTypeList() {
      this.loading = true;
      const {data: res} = await this.$http.get("/bgClient/findBgClientTypeList");
      let validData = [];
      if (Array.isArray(res)) {
        validData = res;
      } else if (typeof res === 'object' && res.success) {
        validData = res.data || [];
      }
      if (Array.isArray(validData)) {
        this.BgClinetType = validData.map(item => ({
          value: item.clientTypeId,
          label: item.options
        }));
      }
    },
    //加载客户来源列表
    async getAllBgSourceList() {
      this.loading = true;
      const {data: res} = await this.$http.get("/bgClient/findBgSourceList");
      let validData = [];
      if (Array.isArray(res)) {
        validData = res;
      } else if (typeof res === 'object' && res.success) {
        validData = res.data || [];
      }
      if (Array.isArray(validData)) {
        this.BgSourceList = validData.map(item => ({
          value: item.sourceId,
          label: item.options
        }));
      }
    },
    //加载客户进线表
    async getAllBgClientCoilInList() {
      this.loading = true;
      const {data: res} = await this.$http.get("/bgClient/findBgClientCoilIn");
      let validData = [];
      if (Array.isArray(res)) {
        validData = res;
      } else if (typeof res === 'object' && res.success) {
        validData = res.data || [];
      }
      if (Array.isArray(validData)) {
        this.BgClientCoilIn = validData.map(item => ({
          value: item.clientCoilInId,
          label: item.options
        }));
      }
    },
    //加载客户状态下拉框
    async getAllClientStatusList() {
      this.loading = true;
      const {data: res} = await this.$http.get("/bgClient/findBgClientStatus");
      let validData = [];
      if (Array.isArray(res)) {
        validData = res;
      } else if (typeof res === 'object' && res.success) {
        validData = res.data || [];
      }
      if (Array.isArray(validData)) {
        this.BgClientStatus = validData.map(item => ({
          value: item.clientStatusId,
          label: item.options
        }));
      }
    },
    //加载售后下拉框
    async getAllCompanyList() {
      this.loading = true;
      const {data: res} = await this.$http.get("/clientConcern/getEmployees");
      let validData = [];
      if (Array.isArray(res)) {
        validData = res;
      } else if (typeof res === 'object' && res.success) {
        validData = res.data || [];
      }
      if (Array.isArray(validData)) {
        this.company = validData.map(item => ({
          value: item.empId,
          label: item.nickName
        }));
      }
    },
    //打开新建客户对话框
    openAddDialog() {
      this.dialogTitle = "新建客户";
      // 重置客户表单数据
      this.clearAddClientData();
      // 打开对话框并清除验证错误信息
      this.dialogVisible = true;
      // 使用 $nextTick 来确保清除验证在视图更新后执行
      this.$nextTick(() => {
        this.$refs.clientForm.clearValidate(); // 清除表单的验证错误信息
      });
    },
    //清除添加客户数据
    clearAddClientData() {
      this.clientForm = {
        clientName: "", // 客户名称
        linkman: "", // 联系人
        phone: "", // 客户手机
        company: "", // 所属公司
        inDustryId: null,
        clientTypeId: null,
        clientCoilInId: null,
        sourceId: null,
      }
    },
    //打开编辑客户对话框
    openEditDialog(client) {
      this.dialogTitle = "编辑客户";
      this.editClientForm = {
        clientId: client.clientId,
        clientName: client.clientName,
        linkman: client.linkman,
        phone: client.phone,
        company: client.company,
        remark: client.remark,
        inDustryId: client.inDustryId,
        clientTypeId: client.clientTypeId,
        clientCoilInId: client.clientCoilInId,
        sourceId: client.sourceId,
        clientStatusId: client.clientStatusId,
        intention: client.intention,
      };
      this.getClientFollow(client.clientId);
      this.drawer_details = true;
      this.$nextTick(() => {
        this.$refs.editClientForm.clearValidate(); // 清除表单的验证错误信息
      });
    },
    /**
     * 处理选择变化事件
     * @param {Array} val - 选中的客户数据数组
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /**
     * 处理每页显示条数变化事件
     * @param {Number} newSize - 新的每页显示条数
     */
    handleSizeChange(newSize) {
      this.queryMap.pageSize = newSize;
      this.getClientList();
    },
    /**
     * 处理当前页码变化事件
     * @param {Number} current - 当前页码
     */
    handleCurrentChange(current) {
      this.queryMap.pageNum = current;
      this.getClientList();
    },
    /**
     * 重置查询条件
     */
    reset() {
      this.queryMap = {
        pageNum: 1, // 当前页码
        pageSize: 10, // 每页显示条数
        clientName: '',
        linkman: '',
        phone: null,
        inDustryId: null,
        sourceId: null,
        clientTypeId: null,
        employeeIdAftermarket: null,
        clientNo: '',
        intention: null,
        clientCoilInId: null,
        startTime: '',
        endTime: '',
      };
      this.value2 = [];
      this.getClientList();
    },
    /**
     * 查询客户数据
     */
    searchCustomer() {
      this.queryMap.pageNum = 1;
      this.getTime();
      this.getClientList();
    },
    getTime() {
      if (this.value2 != null && this.value2.length === 2) {
        console.log("时间：", this.value2);
        // 格式化开始和结束时间
        this.queryMap.startTime = this.formatDate(this.value2[0], false); // 开始日期
        this.queryMap.endTime = this.formatDate(this.value2[1], true);    // 结束日期
      } else {
        this.queryMap.startTime = "";
        this.queryMap.endTime = "";
      }
    },
// 定义一个格式化时间的函数（格式为 yyyy-MM-dd）
    formatDate(date, isEnd) {
      if (date != null) {
        let formattedDate = new Date(date); // 复制一份新的日期对象，避免修改原始日期
        if (isEnd) {
          // 对结束时间加一天，以确保区间包括结束日期当天
          formattedDate.setDate(formattedDate.getDate() + 1);
        }
        const year = formattedDate.getFullYear();
        const month = ('0' + (formattedDate.getMonth() + 1)).slice(-2);
        const day = ('0' + formattedDate.getDate()).slice(-2);
        return `${year}-${month}-${day}`;
      }
      return null;
    },
    /**
     * 客户跟进逻辑
     */
    followUp(clientId) {
      this.clientFollow = {
        clientId: clientId,
        followContent: '',
        remindTime: '',
      }
      this.isVisible_follow = true;
    },
  },
  created() {
    this.getClientList();
    this.getAllBgIndustryList();
    this.getAllBgClientTypeList();
    this.getAllBgSourceList();
    this.getAllBgClientCoilInList();
    this.getAllCompanyList();
    this.getAllClientStatusList();
  },
};
</script>

<style scoped>
.hint {
  margin-left: 2vh;
  font-weight: 400;
  font-size: 12px;
  color: red;
}

.popups {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0%;
  left: 0%;
  background-color: #00000042;
  z-index: 100;
}

.popups .el-main {
  background-color: #fff;
  margin: 15vh auto;
}

.popups .el-main .header {
  display: flex;
  justify-content: center;
  margin-bottom: 2vh;
}

.popups .el-main .header button {
  flex-shrink: 0; /* 防止收缩 */
  font-size: 3vh;
  height: 4.6vh;
  border: none;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-row .el-col {
  font-size: 14px;

  label {
    color: #5e6d82;
  }
}
</style>